package com.libupdateapp;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import android.support.v4.content.PermissionChecker;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.MimeTypeMap;
import android.widget.ProgressBar;
import android.widget.Toast;


import java.io.File;

/**
 * 升级app
 * Created by Administrator on 2016/9/27.
 */
public class UpdateAppManager {
    // 文件分隔符
    private static final String FILE_SEPARATOR = "/";
    // 外存sdcard存放路径
    private static String FILE_PATH ;
//    private static final String FILE_PATH = MyApplication.getContext().getCacheDir().getAbsolutePath() ;
    // 更新应用版本标记
    private static final int UPDARE_TOKEN = 0x29;
    // 准备安装新版本应用标记
    private static final int INSTALL_TOKEN = 0x31;

    private Activity mActivity;
    private String message = "检测到本程序有新版本发布，建议您更新！";
    // 下载应用的进度条
    private ProgressBar progressBar;
    // 进度条的当前刻度值
    private int curProgress;
    // 用户是否取消下载
    private boolean isCancel;
    private String DownLoadAppUrl = "";
    // 需要下载的app网址
    private String DL_ID = "download";
    // 下载应用的对话框
    private Dialog dialog;
    private DownloadManager downloadManager;
    private SharedPreferences prefs;
    private String mAppName;
    /**
     * 如果服务器不支持中文路径的情况下需要转换url的编码。
     *
     * @param string
     * @return
     */

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 这里可以取得下载的id，这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
            Log.v("intent",
                    ""
                            + intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, 0));
            queryDownloadStatus();
        }
    };

    public UpdateAppManager(Activity  activity, String AppUrl,@NonNull String appName) {
        this.mActivity = activity;
        this.DownLoadAppUrl = AppUrl;
        FILE_PATH =activity.getExternalCacheDir()+ FILE_SEPARATOR + "autoupdate";
        mAppName=appName;
    }


    public static void installApk(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//android7.0
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName()+".fileprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            context.startActivity(intent);
        }
    }

    //清除数据
    private void DODM() {
        //同样，在读取SharedPreferences数据前要实例化出一个SharedPreferences对象
        SharedPreferences sharedPreferences = mActivity.getSharedPreferences("downsize", Activity.MODE_PRIVATE);
        //实例化SharedPreferences.Editor对象（第二步）
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        //提交当前数据
        editor.commit();

    }

    /**
     * 检测应用更新信息
     */
    public void checkUpdateInfo() {
//        if(haveTheApk()){
//            installApp();
//        }else{
//            showNoticeDialog();
//        }

//        if(haveTheApk()){//是否已经下载了apk
//            Log.v("archiveFilePath",""+getUninatllApkInfo(mActivity));
//            if(getUninatllApkInfo(mActivity)){
//                installApp();
//                return;
//            }
//
//        }

        switch (NetWorkUtils.getAPNType(mActivity)) {
            case 0://没有网络
                break;
            case 1://WIFI网络
                showNoticeDialog();
                break;
            case 2://3G网络
                showNoticeDialog();
                break;
            case 3://2G网络
                new AlertDialog.Builder(mActivity).setTitle("提示")
                        .setMessage("您正处于移动网络，继续下载将产生流量消耗，建议使用WLAN下载")
                        .setPositiveButton("继续下载", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                showDownloadDialog();
                            }
                        }).setNegativeButton("先不下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        mActivity.finish();
                        dialog.dismiss();
                    }
                }).create().show();
                break;
            default:
                showNoticeDialog();
                break;
        }
    }

    /**
     * 显示提示更新对话框
     */
    private void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);

        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                }
                return false;
            }
        });
        builder.setTitle("软件版本更新")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDownloadDialog();
                    }
                }).setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                mActivity.finish();
                dialog.dismiss();
            }
        }).create().show();
    }

    /**
     * 显示下载进度对话框
     */
    private void showDownloadDialog() {
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        DL_ID=DL_ID+System.currentTimeMillis();
        if (PermissionChecker.checkSelfPermission(mActivity.getApplicationContext(), "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) {// 不允许
            boolean isTip = ActivityCompat.shouldShowRequestPermissionRationale(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (!isTip) {// 表明用户没有彻底禁止弹出权限请求
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){//Android6.0（SDK23）
                    ActivityCompat.requestPermissions(mActivity,new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"},1231);
                }else {
                    // 这里一般会提示用户进入权限设置界面
                    AppSetting.showNoticeDialog(mActivity,"设置","存储权限被禁用，请打开权限，否则无法更新。");
                }
            } else {// 表明用户已经彻底禁止弹出权限请求
                // 这里一般会提示用户进入权限设置界面
                AppSetting.showNoticeDialog(mActivity,"设置","存储权限被禁用，请打开权限，否则无法更新。");
//                ActivityCompat.requestPermissions(mActivity,new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"},1231);
            }
              return;
        }
        downloadManager = (DownloadManager) mActivity.getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
        prefs = PreferenceManager.getDefaultSharedPreferences(mActivity.getApplicationContext());

        if (!prefs.contains(DL_ID)) {
            // 开始下载
            Uri resource = Uri.parse(DownLoadAppUrl);
            DownloadManager.Request request = new DownloadManager.Request(
                    resource);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                    | DownloadManager.Request.NETWORK_WIFI);
            request.setAllowedOverRoaming(false);
            // 设置文件类型
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            String mimeString = mimeTypeMap
                    .getMimeTypeFromExtension(MimeTypeMap
                            .getFileExtensionFromUrl(DownLoadAppUrl));
            request.setMimeType(mimeString);
            // 在通知栏中显示
            request.setShowRunningNotification(true);
            request.setVisibleInDownloadsUi(true);
            // sdcard的目录下的download文件夹

            //lauer  6.0之后写入权限认证
        /*    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(MyApplication.getContext(), "android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_GRANTED) {// 允许
                    request.setDestinationInExternalPublicDir("/hd/",
                            "好融.apk");
                    request.setTitle("好融");
                    long id = downloadManager.enqueue(request);
                    // 保存id
                    prefs.edit().putLong(DL_ID, id).commit();

                } else if (PermissionChecker.checkSelfPermission(mActivity, "android.permission.WRITE_EXTERNAL_STORAGE") == PackageManager.PERMISSION_DENIED) {//拒绝
                    verifyStoragePermissions(mActivity);
                }
            } else {*/
            //内文件 暂时设定
//            request.setDestinationInExternalPublicDir("/hd/",
//                    MyApplication.getContext().getResources().getString(R.string.app_name)+".apk");
            File file = new File(FILE_PATH);
            if (!file.exists()) {
                Log.i("FILE_PATH===000", "downloadApk: "+FILE_PATH);
                //通过file的mkdirs()方法创建<span style="color:#FF0000;">目录中包含却不存在</span>的文件夹
                file.mkdirs();
            }else {
                Log.i("FILE_PATH===333", "downloadApk: "+FILE_PATH);
            }
            request.setDestinationInExternalPublicDir(FILE_PATH,
                    mAppName + System.currentTimeMillis() + ".apk");

            request.setTitle(mAppName);
            long id = downloadManager.enqueue(request);
            // 保存id
            prefs.edit().putLong(DL_ID, id).commit();

            //lauer


        } else {
            // 下载已经开始，检查状态
            Log.e("queryDownloadStatus", "queryDownloadStatus");
            queryDownloadStatus();
        }

        mActivity.getApplicationContext().registerReceiver(receiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private void queryDownloadStatus() {
        System.out.println("queryDownloadStatus---------------");
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(prefs.getLong(DL_ID, 0));
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c
                    .getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    Log.v("down", "STATUS_PAUSED");
                case DownloadManager.STATUS_PENDING:
                    Log.v("down", "STATUS_PENDING");
                case DownloadManager.STATUS_RUNNING:
                    // 正在下载，不做任何事情
                    Log.v("down", "STATUS_RUNNING");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    // 完成
                    int fileUriIdx = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                    String fileUri = c.getString(fileUriIdx);
                    String fileName = null;
                    if (Build.VERSION.SDK_INT > 23) {
                        if (fileUri != null) {
                            fileName = Uri.parse(fileUri).getPath();
                        }
                    } else {
                        //Android 7.0以上的方式：请求获取写入权限，这一步报错
                        //过时的方式：DownloadManager.COLUMN_LOCAL_FILENAME
                        int fileNameIdx = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
                        fileName = c.getString(fileNameIdx);
                    }
                    Log.v("down", "下载完成 " + fileName);
//                    installApkss(new File(dir));
//                    修改 2018-2-6 17:05:56
                    installApk(mActivity.getApplicationContext(), new File(fileName));
                    break;
                case DownloadManager.STATUS_FAILED:
                    // 清除已下载的内容，重新下载
                    Toast.makeText(mActivity.getApplicationContext(),"下载失败",Toast.LENGTH_SHORT).show();
                    Log.v("down", "STATUS_FAILED");
                    downloadManager.remove(prefs.getLong(DL_ID, 0));
                    prefs.edit().clear().commit();
                    break;
            }
        }
    }

}